package com.zjzywl.smoke.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.validation.Valid;
import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zjzywl.smoke.repository.DeviceRepository;
import com.zjzywl.smoke.repository.DeviceStatusHistoryRepository;
import com.zjzywl.smoke.util.RequestBean;
import com.zjzywl.smoke.util.WebResult;
import com.zjzywl.smoke.entity.Device;
import com.zjzywl.smoke.entity.DeviceStatusHistory;

@RestController
@RequestMapping(value = "/deviceStatusHistory")
public class DeviceStatusHistoryController {

	@Autowired
	private DeviceStatusHistoryRepository devStaRepository;

	@Autowired
	private DeviceRepository dRepository;

	private Boolean addH = true;
	private Boolean addT = true;

	@PostMapping(value = "/data/list")
	  
	public WebResult getList() {
		List<DeviceStatusHistory> devStaHistorys = devStaRepository.findAll();
		try {
			return WebResult.OK(devStaHistorys);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	@GetMapping(value = "/list")
	public java.util.List<DeviceStatusHistory> List(Model model) {
		List<DeviceStatusHistory> devStaHistorys = devStaRepository.findAll();
		return devStaHistorys;
	}

	// 通过设备查找历史
	@PostMapping(value = "/listByDeviceId")
	public ResponseEntity<java.util.List> findHistoryByDeviceId(Model model, @PathParam("deviceId") Integer deviceId) {
		List<DeviceStatusHistory> history = devStaRepository.findHistoryByDevice(deviceId);
		
		return new  ResponseEntity<List>(history, HttpStatus.CREATED);
	}

	// 通过状态查找历史
	@PostMapping(value = "/listByStatus")
	public ResponseEntity<java.util.List> findHistoryByStatus(Model model, @PathParam("status") Integer status) {
		List<DeviceStatusHistory> history = devStaRepository.findHistoryByStatus(status);
		model.addAttribute("devStaHistorys", history);
		return  new  ResponseEntity<List>(history, HttpStatus.CREATED);
	}

	// 通过各种设备和时间查找历史
	@PostMapping(value = "/listByCondition")
	public ResponseEntity<java.util.List> findHistoryByCondition( @Valid RequestBean requestBean) throws ParseException {
		Integer deviceId = requestBean.getDeviceId();
			Date et=requestBean.getEt();
			Date lt=requestBean.getLt();
			java.util.List<DeviceStatusHistory> history =null;
			String address = requestBean.getAddress();
			if (deviceId ==null) {
				 history  = devStaRepository.findHistoryByTime(et, lt, address);
			} else {
				history = devStaRepository.findHistoryByCondition(et, lt, deviceId, address);
			}
		return new  ResponseEntity<List>(history, HttpStatus.CREATED);
	}

	// 通过地址模糊查询
	@PostMapping(value = "/listByAddress")
	public java.util.List<DeviceStatusHistory> findHistoryByAddress(Model model, @PathParam("address") String address) {
		model.addAttribute("devStaHistorys", devStaRepository.findHistoryByAddress(address));
		
		return devStaRepository.findHistoryByAddress(address);
	}

	// 通过各种设备编码和时间段查找历史
	@GetMapping(value = "/listByTimeAndCode")
	  
	public WebResult findHistoryByTimeAndCode(Model model, @PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("devCode") String devCode) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		List<DeviceStatusHistory> dshs = devStaRepository.findHistoryByTimeAndCode(bTime, eTime, devCode);
		try {
			return WebResult.OK(dshs);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}

	}

	// 通过各种设备编码和时间段查找历史
	@GetMapping(value = "/listByTimeAndCode/sorting")
	  
	public WebResult findHistoryByTimeAndCodeAndBySorting(Model model, @PathParam("beginTime") String beginTime,
			@PathParam("endTime") String endTime, @PathParam("devCode") String devCode) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date bTime = format.parse(beginTime);
		Date eTime = format.parse(endTime);
		List<Object> dshs = devStaRepository.findHistoryByTimeAndCodeAndDataNotNull(bTime, eTime, devCode);

		try {
			return WebResult.OK(dshs);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	@GetMapping(value = "/mock/go")
	  
	public String mock(@PathParam("count") Integer count, @PathParam("interval") Integer interval,
			@PathParam("dev") String dev) throws InterruptedException {

		// devStaRepository.deleteByMock();

		String devCode = dev;// "c4cd82ff6c29c402";
		Device device = dRepository.findByDeviceCode(dev);
		if (device == null) {
			System.out.println("找不到编号为：[" + devCode + "]的设备");
			return "找不到编号为" + devCode + "的设备";
		}
		int j = 0;
		Integer tempX = 0, tempY = 0;
		for (int i = 0; i < count; i++) {
			// 保存历史状态信息
			DeviceStatusHistory dsh = new DeviceStatusHistory();
			dsh.setDevCode(dev);
			dsh.setDevice(device);

			Integer x = mockH(tempX);// (int)(Math.random()*j);
			tempX = x;
			Integer y = mockT(tempY);// (int)(Math.random()*j);
			tempY = y;

			dsh.setHumidity(x.toString());
			dsh.setTemperature1(y.toString());

			Date d = new Date();

			Calendar cal = Calendar.getInstance();
			cal.setTime(d);
			cal.add(Calendar.MINUTE, i * interval);// 24小时制
			d = cal.getTime();

			dsh.setReturnTime(d);
			dsh.setStatus(999);
			dsh.setLight("0");
			dsh.setVoltage("0");
			dsh.setSpace("0");
			dsh.setTemperature("0");
			devStaRepository.save(dsh);
			Thread.sleep(1);
			j++;
			if (j > 100) {
				j = 0;
			}
		}
		return "mock完成";
	}

	@GetMapping(value = "/mock/delete")
	  
	public String mockdelete() {
		devStaRepository.deleteByMock();
		return "ok";
	}

	private Integer mockH(Integer lastV) {
		Integer v = 0;
		if (addH) {
			v = lastV + getRandom(1, 3);
		} else {
			v = lastV - getRandom(1, 3);
		}

		if (lastV > 32) {
			addH = false;
		} else if (lastV < 8) {
			addH = true;
		}

		return v;
	}

	private Integer mockT(Integer lastV) {
		Integer v = 0;
		if (addT) {
			v = lastV + getRandom(1, 3);
		} else {
			v = lastV - getRandom(1, 3);
		}

		if (lastV > 32) {
			addT = false;
		} else if (lastV < 8) {
			addT = true;
		}

		return v;
	}

	private Integer getRandom(int min, int max) {
		Random random = new Random();
		int s = random.nextInt(max) % (max - min + 1) + min;
		return s;

	}

	// 通过时间查找
	// @PostMapping(value="/listByTime")
	//   
	// public WebResult findHistoryByTime(
	// @PathParam("earlyTime") String earlyTime,
	// @PathParam("lateTime") String lateTime) {
	// try {
	// //时间条件
	// Date et = new Date(0);
	// Date lt = new Date();
	// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	// if(earlyTime.length()>0) {
	// et = sdf.parse(earlyTime);
	// }
	// if(lateTime.length()>0) {
	// lt = sdf.parse(lateTime);
	// }
	// List<DeviceStatusHistory> devStaHistorys =
	// devStaRepository.findHistoryByTime(et,lt);
	// return WebResult.OK(devStaHistorys);
	// } catch (ParseException e) {
	// return WebResult.FAIL(e.getMessage());
	// }
	// }
}
